package LeetCode.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * 无重复字符的最长子串
 * acbcfaecd
 * @author: leiwenkang02@meituan.com
 * @date: 2018/8/28
 * @time: 18:00
 */
public class Test03无重复字符的最长子串 {
    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("abcabcbb"));
    }

    public static int lengthOfLongestSubstring2(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }

        Map<Character, Integer> map = new HashMap<>();

        int longestLength = 0;
        int j = 0;
        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                //这里为何
                j = Math.max(j, map.get(s.charAt(i)) + 1);
            }
            map.put(s.charAt(i), i);
            longestLength = Math.max(longestLength, i - j + 1);
        }

        return longestLength;
    }

    public static int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        Map<Character, Integer> map = new HashMap<>();
        int longestLenth = 0;
        int j = 0;
        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))){
               j = Math.max(j, map.get(s.charAt(i)) + 1);
            }
            map.put(s.charAt(i), i);
            longestLenth = Math.max(longestLenth, i - j + 1);
        }

        return longestLenth;
    }
}
